package eu.orangeflash.webapis.xmlrpc
{
	import flash.events.EventDispatcher;
	
	import eu.orangeflash.webapis.events.XMLRPCEvent;

	public class Client
	extends EventDispatcher
	implements IClient
	{
		protected var url:String;
		protected var result:IMethodResponse
		
		public function Client()
		{
		}
		
		[Bindable]
		public function set serviceURL(value:String):void
		{
			url = value;
		}
		public function get serviceURL():String
		{
			return url;
		}
		
		[Bindable(event="result")]
		public function get lastResult():IMethodResponse
		{
			return result;
		}
		
		public function invoke(methodName:String,...args):IMethodCall
		{
			var result:MethodCall = new MethodCall(this);
				result.addEventListener(XMLRPCEvent.RESULT, onResult);
				result.addEventListener(XMLRPCEvent.FAULT, onFault);
				result.invoke(methodName,args);
				
			return result;
		}
		
		protected function onResult(event:XMLRPCEvent):void
		{
			event.methodCall.removeEventListener(XMLRPCEvent.RESULT, onResult);
			result = event.methodCall.result;
			dispatchEvent(new XMLRPCEvent(XMLRPCEvent.RESULT, this, event.methodCall));
		}
		
		protected function onFault(event:XMLRPCEvent):void
		{
			event.methodCall.removeEventListener(XMLRPCEvent.FAULT, onResult);
			dispatchEvent(new XMLRPCEvent(XMLRPCEvent.FAULT, this, event.methodCall));
		}
	}
}